﻿using Abp.Domain.Uow;
using Abp.Events.Bus;
using Abp.Events.Bus.Entities;
using System;

namespace AbpProjectTemplate.Components.Events.Entities
{
    public class AppEntityChangeEventHelper : EntityChangeEventHelper
    {
        public AppEntityChangeEventHelper(IUnitOfWorkManager unitOfWorkManager) : base(unitOfWorkManager)
        {

        }

        protected virtual void TriggerChangeEvent(Type genericEventType, Type entityType, params object[] entityValues)
        {
            var eventType = genericEventType.MakeGenericType(entityType);
            this.EventBus.Trigger(eventType, (IEventData)Activator.CreateInstance(eventType, entityValues));
        }

        public void TriggerEntityChangeCheckEvent(AppEntityChangeEntry changeEntry)
        {
            if (changeEntry.ChangeType == EntityChangeType.Created)
                this.TriggerChangeEvent(typeof(EntityCreateEventData<>), changeEntry.Entity.GetType(), changeEntry.Entity);
            else if (changeEntry.ChangeType == EntityChangeType.Updated)
                this.TriggerChangeEvent(typeof(EntityUpdateEventData<>), changeEntry.Entity.GetType(), changeEntry.Entity, changeEntry.OriginalEntity);
            else if (changeEntry.ChangeType == EntityChangeType.Deleted)
                this.TriggerChangeEvent(typeof(EntityDeleteEventData<>), changeEntry.Entity.GetType(), changeEntry.Entity);
        }
    }
}
